package kr.saeildamil.androidforstudy2.ch20.common;

import kr.saeildamil.androidforstudy2.R;
import kr.saeildamil.androidforstudy2.ch20.PlanetDescActivity;
import android.app.FragmentManager;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class PlanetListFragment extends ListFragment {

	String[] planets;
	int mLastIndex;
	boolean mMultipane;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		planets = getResources().getStringArray(R.array.planet);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_activated_1, planets));
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		if (savedInstanceState != null) {
			mLastIndex = savedInstanceState.getInt("lastindex");
		}

		// Activity 참조
		View descPanel = getActivity().findViewById(R.id.ch20_multipanewidth_descpanel);
		if (descPanel != null && descPanel.getVisibility() == View.VISIBLE) {
			mMultipane = true;
			onListItemClick(getListView(), null, mLastIndex, 0);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("lastindex", mLastIndex);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		mLastIndex = position;
		getListView().setItemChecked(position, true);
		
		if(mMultipane){
			FragmentManager fm = getFragmentManager();
			PlanetDescFragment df = (PlanetDescFragment) fm.findFragmentById(R.id.ch20_multipanewidth_descpanel);
			if(df==null || df.mNowIndex != position){
				df = PlanetDescFragment.newInstance(position);
				fm.beginTransaction().replace(R.id.ch20_multipanewidth_descpanel, df).commit();
			}
		}else{
				Intent intent = new Intent(getActivity(), PlanetDescActivity.class);
				intent.putExtra("index", position);
				startActivity(intent);
			}
		}
	}

